<template>
    <div id="add-edit-model">
        <el-dialog
            :title="titleCon"
            v-model="isUseDialog" 
            draggable :close-on-click-modal="false" :close-on-press-escape="false"
            width="50%" 
            :before-close="handleClose"
            :destroy-on-close="true"
            @close="clean"
        >
            <template v-if="titleCon === '编辑'">
                <el-divider content-position="left">基本信息</el-divider>
            </template>

            <el-form :model="ruleForm" ref="ruleFormRef" size="default" label-width="80px" :rules="rules">
                <el-row :gutter="35">
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="员工名称" prop="v_EmpName" :label-width="formLabelWidth">
                            <el-select 
                                v-model="ruleForm.v_EmpName" 
                                filterable 
                                class="m-2" 
                                value-key="id"
                                placeholder="员工名称" 
                                @change="empChange"
                                popper-class="set-select"
                                :popper-append-to-body="false"
                            >
                                <el-option
                                    v-for="item in empOption"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="工种名称" prop="v_WorkTypeName" :label-width="formLabelWidth">
                            <el-select 
                                v-model="ruleForm.v_WorkTypeName" 
                                filterable 
                                class="m-2" 
                                placeholder="请选择工种名称" 
                                value-key="n_Id"
                                @change="typeChange"
                                popper-class="set-select"
                                :popper-append-to-body="false"
                            >
                                <el-option
                                    v-for="item in typeOptions"
                                    :key="item.n_Id"
                                    :label="item.v_WorkName"
                                    :value="item.n_Id"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="发证机关" prop="v_IssuingAuthority" :label-width="formLabelWidth">
                            <el-input v-model="ruleForm.v_IssuingAuthority" placeholder="发证机关" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="证书编号" prop="v_IssuingCertificate_No" :label-width="formLabelWidth">
                            <el-input v-model="ruleForm.v_IssuingCertificate_No" placeholder="证书编号" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="证书到期时间" prop="d_NextReview_Date" :label-width="formLabelWidth">
                            <el-date-picker
                                v-model="ruleForm.d_NextReview_Date"
                                type="date"
                                value-format="YYYY-MM-DD"
                                placeholder="选择日期">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="提前提醒天数" prop="i_NoticedDays" :label-width="formLabelWidth">
                            <el-input-number style="width: 100%;"  v-model="ruleForm.i_NoticedDays" :min="0" :max="1000" placeholder="提前提醒天数"  />
                        </el-form-item>
                    </el-col>
                    <!-- <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="特种工作证书" :label-width="formLabelWidth">
                            <div class="upload-d">
                                <el-upload
                                    ref="uploadFileOne"
                                    action="#"
                                    accept=".jpg,.png,.jpeg"
                                    :multiple="false"
                                    :show-file-list="false"
                                    :auto-upload='false'
                                    class="upload-style"
                                    :on-change="certificateChange"
                                    style="width:100%"
                                >
                                    <el-input v-if="!isViewOne" readOnly slot="" placeholder="特种工作证书" />
                                    <el-input v-else v-model="certificateVal" readOnly slot="" placeholder="特种工作证书" />
                                </el-upload>
                                <template v-if="isViewOne">
                                    <div class="icon-d upload-b">
                                        <el-tooltip effect="dark" content="移除" placement="top">
                                            <el-icon @click="cancelDepClickOne" style="background: unset !important;cursor:pointer;">
                                                <Delete />
                                            </el-icon>
                                        </el-tooltip>
                                    </div>
                                </template>
                            </div>
                        </el-form-item>
                    </el-col> -->
                </el-row>
            </el-form>

            <template v-if="titleCon === '编辑'">
                <el-divider content-position="left"> 历史证书附件 </el-divider>
                <el-table class="table-s" :data="fileListArr" style="width: 100%" border>
                    <el-table-column min-width="160" prop="name" :show-overflow-tooltip="true" label="附件名称"  align="center" />
                    <el-table-column min-width="270" prop="path" :show-overflow-tooltip="true" label="附件路径"  align="center" />
                    <el-table-column min-width="120" prop="suffix" :show-overflow-tooltip="true" label="附件后缀"  align="center" />
                    <el-table-column min-width="120" prop="suffix" :show-overflow-tooltip="true" label="缩略图"  align="center">
                        <template #default="scope">
                            <img style="width: 20px;height: 20px;" :src="pathData + scope.row.path" />
                        </template>
                    </el-table-column>
                    <el-table-column min-width="160" prop="createdTime" :show-overflow-tooltip="true" label="上传时间"  align="center" />
                    <el-table-column min-width="120" prop="createdUserName" :show-overflow-tooltip="true" label="上传人"  align="center" />
                    <el-table-column min-width="120" :show-overflow-tooltip="true" label="操作"  align="center"  fixed="right">
                        <template #default="scope">
                            <el-link target="_blank" :href="pathData + scope.row.path">预览</el-link>
                            <el-button @click="deleteHandle(scope.row.id)" class="icon-e" icon="ele-Delete" size="small" text type="danger"> 删除 </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </template>

            <template #footer>
                <el-button @click="cancelUseClick">取消</el-button>
                <el-button :loading="repeatDis" :disabled="repeatDis" @click="submitForm(ruleFormRef)" type="primary">提交</el-button>
            </template>
        </el-dialog>
    </div>
</template>
<script lang="ts">
import { defineComponent, ref, Ref , reactive , computed , toRef , toRefs , toRaw , onMounted , watch } from 'vue';
import { FormInstance, FormRules , ElMessage ,ElMessageBox , ElButton, ElCol, ElDatePicker, ElDialog, ElDivider, ElForm, ElFormItem, ElInput, ElOption, ElRadio, ElRow, ElSelect, ElTable, ElTableColumn } from 'element-plus';
import { EmpWorkTypeAdd , WorkTypeGetList , SysEmpSelector , EmpWorkTypeUpdate , sysFileInfoDelete } from '/@/api/centerControl/oms';
import useCurrentInstance from '/@/utils/hook/useCurrentInstance';

/*** 定义接口基础数据类型 */
interface formType {
    repeatDis: Boolean,
    ruleForm: ruleFormType,
}
/*** form 表单数据类型 */
type ruleFormType = {
    n_Id?: Number, // 组件id
    //certificateFile: String, // 特种工作证书
    v_IssuingAuthority: String, // 发证机关(特种作业人员)
    v_IssuingCertificate_No: String, // 证书编号(特种作业人员)
    i_NoticedDays: Number, // 证书编号(特种作业人员)
    n_Certificate_Id: Number, // 证书附件(特种作业人员)
    d_NextReview_Date: String, // 下次复查时间(特种作业人员)

    n_EmpId: Number, // 员工Id
    v_EmpName: String, // 员工姓名(用于显示)

    n_OrgId: Number, // 所属机构id

    n_WorkType_Id: Number, // 工种类型Id (传给接口)
    v_WorkTypeName: String, // 工种类型名称
}
export default defineComponent( {
    name: 'add-edit-model',
    components: {},
    props: {
        isUseDialog:{
            type: Boolean,
            default: false,
        },
        repairInfo: {
            type: String,
            default: ''
        }
    },
    setup(props,ctx){
        // const { proxy } = useCurrentInstance();
        // const $t = proxy.$t;

        const titleCon = ref()
        const ruleFormRef = ref()
        const empOption:any = ref([])
        const typeOptions:any = ref([])
        const uploadFileOne:Ref = ref(null)
        const certificateVal = ref()

        const isViewOne = ref(false)
        const showImg = ref(false)
        const fileListArr:any = ref([])
        const pathData = ref(import.meta.env.VITE_API_URL + '/') // 获取地址

        /*** state 引用接口定义基础数据初始值 */
        const state = reactive < formType > ({
            repeatDis: false,
            ruleForm: {} as ruleFormType
        })

         /*** 基础验证 rules */
        const rules = reactive < FormRules > ({
            /*** 放置验证 */
            v_EmpName: [
				{ required: true, message: '请选择人员', trigger: 'change' },
			],
            v_WorkTypeName: [
                { required: true, message: '请选择工种', trigger: 'change' }
            ],
            v_IssuingAuthority: [
                { required: true, message: '请输入发证机关', trigger: 'blur' }
            ],
            v_IssuingCertificate_No: [
                { required: true, message: '请输入证书编号', trigger: 'blur' }
            ],
            i_NoticedDays: [
                { required: true, message: '请输入提前提醒天数', trigger: 'blur' }
            ],
            d_NextReview_Date: [
                { required: true, message: '请选择下次复审时间', trigger: 'change' }
            ],
        })

        /*** empChange 员工下拉框改变事件 */
        const empChange = (val:any) => {
            state.ruleForm.n_EmpId = toRaw(val).id
            state.ruleForm.n_OrgId = toRaw(val).orgId
        }

        /*** typeChange 工种类型下拉框 */
        const typeChange = (val:any) => {
            console.log(val,'val')
            state.ruleForm.n_WorkType_Id = val
        }

        /*** GetInfo 获取所有信息 */
        const GetInfo = async () => {
            let res:any = await WorkTypeGetList()
            let getVal:any = await SysEmpSelector()
            if(res.success){
                console.log(res.data,'工种列表')
                typeOptions.value = res.data
            }
            if(getVal.success){
                console.log(getVal,'getVal')
                empOption.value = getVal.data
            }
        }

        /*** lookImgClick 员工图片预览 */
        const lookImgClick = (val:any) => {
            // window.location.href = 'www.baidu.com' // 覆盖当前页
            window.open(toRaw(pathData.value) + val,'_blank') // 打开新页面
        }

        /*** certificateChange 上传员工照片改变事件 */
        const certificateChange = (item:any,fileList:any) => {
            if (fileList.length > 1) {
                fileList.splice(0, 1); // 当上传文件大于1的时候替换，移除之前的文件（0是要删除数组的下标，1是要删除的数量）
            }
            //state.ruleForm.certificateFile = item.raw
            isViewOne.value = true
            certificateVal.value = item.name
        }

        /*** cancelDepClickOne 人员图像上传移除文件 */
        const cancelDepClickOne = () => {
            ElMessage({
                message: '删除成功',
                type: 'success',
                duration: 1000,
                onClose: () => {
                    //uploadFileOne.value.clearFiles()
                    certificateVal.value = ''
                    isViewOne.value = false
                    showImg.value = false
                   // state.ruleForm.certificateFile = ''
                }
            })
        }

        /*** handleClose 关闭按钮点击事件 */
        const handleClose = () => {
            cancelUseClick()
        }

        /*** cancelUseClick 取消事件 */
        const cancelUseClick = () => {
            clearFileFun()
            ctx.emit('cancelUseClick')
        }

        /*** submitForm 提交事件 */
        const submitForm = (formEl: FormInstance | undefined) => {
            if(!formEl) return
            formEl.validate( async (valid) => {
                if(valid){
                    const setObj: any = toRaw(state.ruleForm)
                    const {v_EmpName , v_WorkTypeName , ...getArr} = setObj
                    for(let i in getArr){
                        if(getArr[i] == null){
                            getArr[i] = ''
                        }
                    }
                    if(props.repairInfo === ''){
                        state.repeatDis = true
                        let res:any = await EmpWorkTypeAdd(getArr)
                        if(res.success){
                            ctx.emit('updateData')
                            ctx.emit('controlUseClick')
                            clearFileFun()
                            state.repeatDis = false
                        }
                    }else{
                        state.repeatDis = true
                        let res:any = await EmpWorkTypeUpdate(getArr)
                        if(res.success){
                            ctx.emit('updateData')
                            ctx.emit('controlUseClick')
                            clearFileFun()
                            state.repeatDis = false
                        }
                    }
                }else{
                    console.log('error submit!')
					return false
                }
            })
        }

        /*** clean 清空数据 */
        const clean = () => {
            ruleFormRef.value.resetFields()
        }
        /*** clearFileFun 清空文件函数 */
        const clearFileFun = () => {
            // 清空文件上传数据
           // uploadFileOne.value.clearFiles()
            certificateVal.value = ''
        }

        /*** 监听isUseDialog的变化 */
        watch(() => props.isUseDialog,(newVal) => {
            if(newVal){
                GetInfo()
                // 重置状态
                state.repeatDis = false
                isViewOne.value = false
                showImg.value = false
                fileListArr.value = []
                // 重置状态

                if(props.repairInfo !== ''){
                    titleCon.value = '编辑'
                    if(JSON.parse(props.repairInfo).certificatePath){
                        isViewOne.value = false
                        showImg.value = false
                        //let filePath = JSON.parse(props.repairInfo).certificatePath
                        let fileArr:any = []
                        // filePath.map((i:any) => {
                        //     let fileData:any = {}
                        //     fileData.id = i.id
                        //     fileData.createdTime = i.createdTime
                        //     fileData.createdUserName = i.createdUserName
                        //     fileData.name = i.path.split('.')[0].split('/')[i.path.split('.')[0].split('/').length -1 ]
                        //     fileData.path = i.path
                        //     fileData.suffix = i.path.split('.')[i.path.split('.').length - 1]
                        //     fileArr.push(fileData)
                        // })
                        fileListArr.value = fileArr
                    }
                    state.ruleForm = JSON.parse(props.repairInfo)
                }else{
                    titleCon.value = '新增'
                    state.ruleForm = {
                        //certificateFile: '', // 特种工作证书
                        v_IssuingAuthority: '', // 发证机关(特种作业人员)
                        v_IssuingCertificate_No: '', // 证书编号(特种作业人员)
                        i_NoticedDays: 0, // 证书编号(特种作业人员)
                        n_Certificate_Id: 0, // 证书附件(特种作业人员)
                        d_NextReview_Date: '', // 下次复查时间(特种作业人员)

                        n_EmpId: 0, // 员工Id
                        v_EmpName: '', // 员工姓名

                        n_OrgId: 0, // 所属机构id
                        n_WorkType_Id: 0, // 工种类型Id（传给接口）
                        v_WorkTypeName: '', // 工种类型名称
                    }
                }
            }
        })

        /*** isUseDialog 响应弹窗的关闭  */
        const isUseDialog = computed(() => {
            return props.isUseDialog
        })

        /*** deleteHandle 删除数据事件 */
        const deleteHandle = async (val: String | Number) => {
            ElMessageBox.confirm('请确定是否删除此条数据','警告',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            )
            .then(async() => {
                let param = {id : val}
                try {
                    let res:any = await sysFileInfoDelete(param)
                    if(res.success){
                        let getArr = toRaw(fileListArr.value).filter((i:any) => {
                            return i.id !== val
                        })
                        fileListArr.value = getArr
                        ctx.emit('updateData')
                    }
                } catch (err) { return }
            })
            .catch(() => {
                ElMessage({
                    type: 'info',
                    message: '已取消',
                })
            })
        }

        return {
            handleClose,
            submitForm,
            cancelUseClick,
            clean,
            ruleFormRef,
            titleCon,
            ...toRefs(state),
            isUseDialog,
            rules,
            typeOptions,
            typeChange,
            formLabelWidth: '120px',
            empOption,
            empChange,
            uploadFileOne,
            certificateChange,
            cancelDepClickOne,
            certificateVal,
            isViewOne,
            showImg,
            lookImgClick,
            pathData,
            fileListArr,
            deleteHandle,
        }
    },
} )
</script>
<style scoped lang="scss">
    :deep(.el-select){
        width: 100%;
    }
    :deep(.el-input){
        width: 100%;
    }
    .table-s{
        :deep(.el-icon){
            margin-right: 0px!important;
            margin-left: 12px!important;
        }
    }
    .upload-d{
        position: relative;
        width: 100%;
        :deep(.el-upload){
            width: 100%;
        }
        .path_look{
            display: block;
            width: 100%;
            border: 1px solid #e4e7ed;
            border-radius: 4px;
            position: absolute;
            left: 0;
            top: 0;
            span{
                display: block;
                margin-left: 15px;  
                color: #606266;
            }
        }
        .upload-in{
            position: absolute;
            left: 0;
            top: 0;
        }
        .upload-b{
            display: flex;
            align-items: center;
            position: absolute;
            top: 10px;
            right: 10px;
            line-height: initial;
            background: unset !important;
            :deep(a){
                background: unset !important;
                margin-right: 10px;
            }
            :deep(span){
                background: unset !important;
            }
        }
    }
</style>